package com.cloudcc.mobile.view.main.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.CApplication;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.impl.ApprovalEngineImpl;
import com.cloudcc.mobile.entity.ChatUser;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.im.UIControl;
import com.cloudcc.mobile.im.ui.AttentionActivity;
import com.cloudcc.mobile.im.ui.GroupsActivity;
import com.cloudcc.mobile.im.ui.GuanzhuActivity;
import com.cloudcc.mobile.manager.ContactsManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.ContactsPresenter;
import com.cloudcc.mobile.util.CharacterParser;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.activity.Myinformation;
import com.cloudcc.mobile.view.activity.UserInfoActivity;
import com.cloudcc.mobile.view.im.ConversationListActivity;
import com.cloudcc.mobile.view.main.MainUIActivity;
import com.cloudcc.mobile.view.mymodel.cowerentity;
import com.cloudcc.mobile.view.mymodel.newcowerEntity;
import com.cloudcc.mobile.weight.ClearEditText;
import com.cloudcc.mobile.weight.SideBar;
import com.cloudcc.mobile.weight.SideBar.OnTouchingLetterChangedListener;
import com.easemob.chat.EMChatManager;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.log.Log;
import com.mypage.utils.ImageLoaderUtils_circle;
import com.mypage.utils.ListDataSave;
import com.mypage.utils.NetStateUtils;
import com.mypage.utils.SaveTemporaryData;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import butterknife.Bind;
import butterknife.OnClick;

import static com.cloudcc.mobile.R.id.cower_group_text;

/**
 * t同事
 *
 * @author lhy
 * @date 2015/12/08/12:00
 */
public class NewCoworkerListFragment extends BaseListFragment implements
        OnClickListener, ExpandableListView.OnChildClickListener,
        ExpandableListView.OnGroupClickListener, PtrHandler, IEventLife {
    private ApprovalEngineImpl engine = new ApprovalEngineImpl();
    protected CharacterParser characterParser;
    private boolean isquliao = RunTimeManager.getInstance().getIsQunLiao();
    private String mEns = RunTimeManager.getInstance().getlanguage();
    // @Bind(R.id.new_load_more_list_view_ptr_frame)
    // protected PtrFrameLayout mRefreshLayout;
    // @Bind(R.id.new_load_more_list_view_container)
    // protected LoadMoreListViewContainer mLoadMoreLayout;
    @Bind(R.id.new_filter_edit)
    protected ClearEditText mClearEditText;
    //
    // @Bind(R.id.headerbar)
    // protected CloudCCTitleBar headerbar;

    // @Bind(R.id.bar_title_text)
    // TextView title;
    private ChatUser user;
    @Bind(R.id.topbar_ts)
    RelativeLayout topbarts;
    @Bind(R.id.cower_qunliao)
    RelativeLayout qunliao;
    @Bind(R.id.cower_guanzhutongshi)
    RelativeLayout guanzhu;

    @Bind(R.id.newcoworexpandablelist)
    ExpandableListView expandablelist;
    @Bind(R.id.cower_sidrbar)
    SideBar sideBar;
    @Bind(R.id.allmenubtn)
    ImageView allmenubtn;
    @Bind(R.id.sousuo_hint)
    TextView sousuo_hint;
    @Bind(R.id.sousuo_bg)
    RelativeLayout sousuo_bg;
    @Bind(R.id.message_num_tz)
    TextView message_num_tz;
    protected int[] colors;
    ListDataSave listdatasave = null;

    @Override
    public void init() {
        // TODO Auto-generated method stub
        EventEngine.register(this);
        super.init();
        // sideBar = (SideBar) findViewById(R.id.sidrbar);
        String[] array = mContext.getResources().getStringArray(
                R.array.logo_colors);
        colors = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            colors[i] = Color.parseColor(array[i]);
        }
        // initRefresh();
        listdatasave = new ListDataSave(getActivity(), "NewCoworkerListFragment");
        if (isquliao) {
            topbarts.setVisibility(View.GONE);
            sousuo_hint.setText(getString(R.string.sousuoshitu));
//            sousuo_bg.setBackgroundColor(getResources().getColor(R.color.white));
        }
        initData();
        requestData();
        addListener();
        initFilter();

    }

    /**
     * 头像切换成功
     *
     * @param event
     */
    boolean isbit = false;
    public Bitmap imgphoto;

    public void onEventMainThread(EventList.UpdateUserEvent event) {
        imgphoto = ((MainUIActivity) getActivity()).imgphoto;
        isbit = true;
    }

    private void initData() {
        // TODO Auto-generated method stub
        int unreadCount = getUnreadMsgCountTotal();
    }

    private void initFilter() {
        characterParser = CharacterParser.getInstance();
        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
                if (mClearEditText.length() > 0) {
                    sousuo_hint.setVisibility(View.GONE);
                } else {
                    sousuo_hint.setVisibility(View.VISIBLE);

                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @OnClick(R.id.cow_right)
    public void onClickRight() {
        EventEngine.post(new MenuToggleEvent(false, true));
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<cowerentity> filterDateList = new ArrayList<cowerentity>();

        List<String> datagroup = new ArrayList<String>();
        Map<String, List<cowerentity>> childmap = new HashMap<String, List<cowerentity>>();
        if (TextUtils.isEmpty(filterStr)) {
//			mClearEditText.setGravity(Gravity.CENTER);
            datagroup.addAll(datagroupnew);
            childmap.putAll(childmapnew);
        } else {
//			mClearEditText.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
            datagroup.clear();
            childmap.clear();
            filterDateList.clear();
            String key = null;
            Log.d("initfileye", "遍历的数据" + childmapnew.size());
            for (Entry<String, List<cowerentity>> entry : childmapnew
                    .entrySet()) {
                List<cowerentity> value = entry.getValue();
                for (int i = 0; i < value.size(); i++) {

                    String name = value.get(i).name;
                    if (name != null
                            && (name.indexOf(filterStr.toString().toLowerCase()) != -1 || characterParser
                            .getSelling(name).startsWith(
                                    filterStr.toString()))) {
                        key = entry.getKey();
                        filterDateList.add(value.get(i));
                        Log.d("initfileye", "添加的数据" + value.get(i).name + ":::"
                                + key);

                    }
                }
                if (key != null && filterDateList.size() > 0) {
                    for (int i = 0; i < filterDateList.size(); i++) {
                        Log.d("zhanshishuju", "展示的数据"
                                + filterDateList.get(i).name + "::" + key);
                    }
                    //为了防止重复新增的list
                    List<cowerentity> filterDateListnew = new ArrayList<cowerentity>();
                    filterDateListnew.addAll(filterDateList);
                    datagroup.add(key);
                    childmap.put(key, filterDateListnew);
                    Log.d("initfileye", "走了几波按摩" + key + "11111111111");
                    key = null;
                    filterDateList.clear();
                }

            }
        }
        Log.d("initfileye",
                "最后的数据::" + childmapnew.size() + "::" + datagroup.size() + "::"
                        + childmap.size());
        if (adapter != null) {
            // onRequestFinish(ListUtils.isEmpty(filterDateList));
            adapter.changeData(datagroup, childmap);
        }
    }

    private void addListener() {
        allmenubtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                EventEngine.post(new MenuToggleEvent(false, false));
            }
        });
        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
            @SuppressLint("NewApi")
            @Override
            public void onTouchingLetterChanged(String s) {
                try {
                    int a = -1;
                    for (int i = 0; i < listnewgroup.size(); i++) {
                        if (s.equals(listnewgroup.get(i))) {
                            a = i;
                        }
                    }
                    if (a != -1) {
                        expandablelist.setSelectedGroup(a);
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        });
        qunliao.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(new Intent(getActivity(), GroupsActivity.class));

            }
        });
        guanzhu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(new Intent(getActivity(), GuanzhuActivity.class));
            }
        });
    }

    protected List<CoworkerEntity> mContactes = new ArrayList<CoworkerEntity>();
    protected ContactsPresenter mContactPresenter = new ContactsPresenter();
    List<cowerentity> cowerentitylist;
    String aa;
    List<String> list = new ArrayList<String>();// 计划是group
    List<String> listnewgroup = new ArrayList<String>();
    List<List<cowerentity>> listshuju = new ArrayList<List<cowerentity>>();
    Map<String, List<cowerentity>> map = new HashMap<String, List<cowerentity>>();
    int tag = 0;

    @Override
    public void requestData() {
        HttpUtils utils = new HttpUtils();

        for (int i = 0; i < 27; i++) {
            if (i < 26) {
                aa = (char) ('a' + i) + "";
            } else {
                aa = "#";
            }
            list.add(aa);

            RequestParams params = new RequestParams();
            params.addBodyParameter("binding", RunTimeManager.getInstance()
                    .getServerBinding());
            params.addBodyParameter("serviceName", "getUserInfoList");

            params.addBodyParameter("code", aa);
            Log.d("request",
                    "链接" + UrlManager.getInterfaceUrl()
                            + GsonUtil.Object2Json(params));
            utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            Log.d("-------------------------", "Failure。。。"
                                    + arg1);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            String result = arg0.result;
                            Log.d("request",
                                    "Success_down:     " + result);
                            Gson gson = new Gson();
                            newcowerEntity ss = gson.fromJson(result,
                                    newcowerEntity.class);
                            try {
                                Log.d("shujushishashend",
                                        ss.data.get(0).pinyin.substring(0, 1));
                                listnewgroup.add(ss.data.get(0).pinyin
                                        .substring(0, 1));
                                map.put(ss.data.get(0).pinyin.substring(0, 1),
                                        ss.data);
//								listdatasave.setDataMap("map", map);
//								listdatasave.setDataList("listnewgroup", listnewgroup);
                                // 排序
                                try {
                                    Collections.sort(listnewgroup);
                                } catch (Exception e) {
                                    // TODO: handle exception
                                }
                                adapter.notifyDataSetChanged();
                                expandablelist.expandGroup(tag);
                                tag++;
                                Log.d("initfileye", "获取数据前" + map.size() + "::"
                                        + childmapnew.size());
                                // 赋值
                                datagroupnew.add(ss.data.get(0).pinyin
                                        .substring(0, 1));
                                childmapnew.put(
                                        ss.data.get(0).pinyin.substring(0, 1),
                                        ss.data);
                                Log.d("initfileye", "获取数据" + map.size() + "::"
                                        + childmapnew.size());

                            } catch (Exception e) {
                            }

                        }
                    });

        }

        adapter = new MyexpandableListAdapter(mContext);
        expandablelist.setAdapter(adapter);
        int groupCount = expandablelist.getCount();
        for (int i = 0; i < groupCount; i++) {
            expandablelist.expandGroup(i);
        }
    }

    // 刷新后使用这个保存之前的总数据。不能使用之前的 会覆盖
    List<String> datagroupnew = new ArrayList<String>();
    Map<String, List<cowerentity>> childmapnew = new HashMap<String, List<cowerentity>>();
    public MyexpandableListAdapter adapter;

    public List<Entry<String, String>> sortMap(final Map<String, String> map) {
        final List<Entry<String, String>> infos = new ArrayList<Entry<String, String>>(
                map.entrySet());

        // 重写集合的排序方法：按字母顺序
        Collections.sort(infos, new Comparator<Entry<String, String>>() {
            @Override
            public int compare(final Entry<String, String> o1,
                               final Entry<String, String> o2) {
                return (o1.getKey().toString().compareTo(o2.getKey()));
            }
        });

        return infos;
    }

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v,
                                int groupPosition, long id) {
        return true;
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v,
                                int groupPosition, int childPosition, long id) {

        return false;
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public int getLayoutId() {
        return R.layout.newcoworferlist;
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content,
                                     View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame,
                expandablelist, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        onRefreshData();
    }

    class MyexpandableListAdapter extends BaseExpandableListAdapter {
        private Context context;
        private LayoutInflater inflater;

        // private Button loadMore;

        public MyexpandableListAdapter(Context context) {
            this.context = context;
            inflater = LayoutInflater.from(context);

        }

        public void changeData(List<String> datagroup,
                               Map<String, List<cowerentity>> childmap) {
            if (listnewgroup != null) {
                listnewgroup.clear();
                // listnewgroup = null;
            }
            if (map != null) {
                map.clear();
                // map=null;
            }
            Log.d("initfileye", "最后的数据222::" + childmapnew.size() + "::"
                    + datagroup.size() + "::" + childmap.size());

            listnewgroup.addAll(datagroup);
            map.putAll(childmap);
            Log.d("isnull", "is:" + listnewgroup != null + "::" + (map != null));
            try {
                Collections.sort(listnewgroup);
            } catch (Exception e) {
                // TODO: handle exception
            }
            notifyDataSetChanged();
            for (int i = 0; i < listnewgroup.size(); i++) {
                expandablelist.expandGroup(i);
            }
            ;
        }

        @Override
        public int getGroupCount() {
            return listnewgroup.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {

            return map.get(listnewgroup.get(groupPosition)).size();

        }

        @Override
        public Object getGroup(int groupPosition) {
            return listnewgroup.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return map.get(listnewgroup.get(groupPosition)).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        public LinearLayout linearLayout;

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            int unreadCount = getUnreadMsgCountTotal();
            GroupHolder groupHolder = null;
            groupHolder = new GroupHolder();
            convertView = inflater.inflate(R.layout.cower_group, null);
            LinearLayout layoutBtn = (LinearLayout) convertView
                    .findViewById(R.id.layoutBtn);

            //群聊
            LinearLayout btnGroup = (LinearLayout) convertView.findViewById(R.id.btnGroup);
            RelativeLayout btnYunXin = (RelativeLayout) convertView.findViewById(R.id.yunxin_ll_x);
            LinearLayout btnAttion = (LinearLayout) convertView.findViewById(R.id.btnAttion);
            Button btnBtnGroup = (Button) convertView.findViewById(R.id.btnBtnGroup);
            Button btnBtnAttion = (Button) convertView.findViewById(R.id.btnBtnAttion);
            TextView immnum = (TextView) convertView.findViewById(R.id.message_numb_x);
            TextView immnum99 = (TextView) convertView.findViewById(R.id.message_numb_x_99);

            linearLayout = (LinearLayout) convertView.findViewById(R.id.groupll);
            if (unreadCount > 0) {
                immnum.setVisibility(View.VISIBLE);
                immnum99.setVisibility(View.GONE);
                immnum.setText(String.valueOf(unreadCount));
                if (unreadCount > 99) {
                    immnum.setVisibility(View.GONE);
                    immnum99.setVisibility(View.VISIBLE);
                }
            } else {
                immnum99.setVisibility(View.GONE);
                immnum.setVisibility(View.GONE);
            }

            groupHolder.textView = (TextView) convertView
                    .findViewById(cower_group_text);
            groupHolder.textView.setText(listnewgroup.get(groupPosition));
            convertView.setTag(groupHolder);
            if (groupPosition == 0 && !isquliao) {
                layoutBtn.setVisibility(View.VISIBLE);
//				btnBtnGroup.setOnClickListener(new OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						// TODO Auto-generated method stub
//						startActivity(new Intent(getActivity(), GroupsActivity.class));
//					}
//				});
                btnGroup.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if ("cc201307019DXlPd701".equals(RunTimeManager.getInstance().getOrgId())) {
                            Toast.makeText(mContext, getResources().getString(R.string.tiyan), Toast.LENGTH_SHORT).show();
                        } else {
                            startActivity(new Intent(getActivity(), GroupsActivity.class));
                        }
                    }

                });
//云信消息
                btnYunXin.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharedPreferences pref = getActivity().getSharedPreferences(
                                "data", 0);
                        SharedPreferences.Editor editor = pref.edit();
                        editor.clear();

                        editor.commit();

                        Intent i = new Intent();
                        i.setClass(context, ConversationListActivity.class);
                        i.putExtra("url", "lyj");
                        startActivity(i);
                    }
                });
                btnBtnAttion.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        startActivity(new Intent(getActivity(), GuanzhuActivity.class));
                    }
                });
                btnAttion.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        startActivity(new Intent(getActivity(), GuanzhuActivity.class));
                    }
                });
            } else {
                layoutBtn.setVisibility(View.GONE);
            }
            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition,
                                 final int childPosition, boolean isLastChild, View convertView,
                                 ViewGroup parent) {
            childHolder holder;
            holder = new childHolder();
            convertView = inflater.inflate(R.layout.cower_item, parent, false);
            holder.textView = (TextView) convertView
                    .findViewById(R.id.cower_item_text);
            holder.image = (ImageView) convertView
                    .findViewById(R.id.cower_image);
            if (isLastChild) {
                holder.line = convertView.findViewById(R.id.cower_item_line);
                holder.line.setVisibility(View.GONE);
            }
            holder.ll = (LinearLayout) convertView.findViewById(R.id.childll);
            holder.ll.setOnClickListener(new OnClickListener() {
                //				String useridx = ContactsManager.getInstance().encodeHXuserName(map.get(listnewgroup.get(groupPosition))
//						.get(childPosition).getId());
                String useridx = map.get(listnewgroup.get(groupPosition))
                        .get(childPosition).getId();

                @Override
                public void onClick(View v) {
                    if (isquliao) {
                        if ("cc201307019DXlPd701".equals(RunTimeManager.getInstance().getOrgId())) {
                            Toast.makeText(mContext, "您好，体验版本无法使用聊天功能", 1).show();

                        } else {
                            if (UserUtils.isMe(useridx)) {
                                if ("en".equals(mEns)) {
                                    Toast.makeText(mContext, "I'm sorry I can not chat with myself...", 0).show();
                                } else {
                                    Toast.makeText(mContext, "对不起不能自己跟自己聊天...", 0).show();
                                }

                            } else {
//									UIControl.openChatUI(mContext, ContactsManager.getInstance().encodeHXuserName(userId),
//											user.getName(), false);

                                UIControl.openChatUI(mContext, ContactsManager.getInstance().encodeHXuserName(useridx), map.get(listnewgroup.get(groupPosition))
                                        .get(childPosition).getName(), false);
                                getActivity().finish();
                            }
                        }
                    } else {
                        SaveTemporaryData.mSmart="";
                        SaveTemporaryData.detailDyamic = "";
                        SaveTemporaryData.GeneralOne = true;
                        Intent intent = new Intent(getActivity(),
                                Myinformation.class);
                        if (RunTimeManager.getInstance().getUserId().equals(map.get(listnewgroup.get(groupPosition))
                                .get(childPosition).getId())) {
                            intent.putExtra("isme", "cowme");
                        }
                        intent.putExtra(
                                UserInfoActivity.KEY_USERID,
                                map.get(listnewgroup.get(groupPosition))
                                        .get(childPosition).getId());
                        intent.putExtra(
                                "name",
                                map.get(listnewgroup.get(groupPosition))
                                        .get(childPosition).getName());
                        mContext.startActivity(intent);
                    }

                }
            });
            holder.textView.setText(map.get(listnewgroup.get(groupPosition))
                    .get(childPosition).name);

//				String url = UrlTools.getTopImage(map
//						.get(listnewgroup.get(groupPosition)).get(childPosition)
//						.getId());
//				ImageLoader.getInstance().displayImage(url, holder.image, ImageLoaderUtils_circle.MyDisplayImageOptions());

//            if (isbit && map.get(listnewgroup.get(groupPosition))
//                    .get(childPosition).getId().equals(RunTimeManager.getInstance().getUserId())) {
//                holder.image.setImageBitmap(imgphoto);
////                holder.image.setImageBitmap(AppContext.topicon);
//            } else {
//
//                String uri = UrlTools.getTopImage(map
//                        .get(listnewgroup.get(groupPosition)).get(childPosition)
//                        .getId());
//                int colorindex = childPosition % colors.length;
//                UserUtils.setLogoRound_z(uri, holder.image, colors[colorindex],
//                        getNickRowName(map.get(listnewgroup.get(groupPosition))
//                                .get(childPosition).name), mContext);
//            }

            try {
                if(AppContext.topicon!=null&&map
                        .get(listnewgroup.get(groupPosition)).get(childPosition)
                        .getId().equals(RunTimeManager.getInstance().getUserId())){
                    holder.image.setImageBitmap(AppContext.topicon);
                }else {
                    String url = UrlTools.getTopImage(map
                            .get(listnewgroup.get(groupPosition)).get(childPosition)
                            .getId());
                    ImageLoader.getInstance().displayImage(url , holder.image, ImageLoaderUtils_circle.MyDisplayImageOptions());
                    Bitmap imgphoto = ImageUtils.toRoundBitmap(UserManager.getManager().getLogoId(map
                            .get(listnewgroup.get(groupPosition)).get(childPosition)
                            .getId()));
                    holder.image.setImageBitmap(imgphoto);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

//			if(map.get(listnewgroup.get(groupPosition)).get(childPosition)
//					.getId().equals(RunTimeManager.getInstance().getUserId())){
////				holder.ll.setVisibility(View.GONE);
////				if(map.get(listnewgroup.get(groupPosition)).size()==1){
////					linearLayout.setVisibility(View.GONE);
////				}else{
////					linearLayout.setVisibility(View.VISIBLE);
////				}
//				holder.image.setImageBitmap(AppContext.topicon);
//			}else {
//				holder.ll.setVisibility(View.VISIBLE);
//			}


            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

    }

    class GroupHolder {
        TextView textView;
    }

    class childHolder {
        TextView textView;
        ImageView image;
        LinearLayout ll;
        View line;

        // Button loadMore;
    }

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    /**
     * 获取用户的 简称 名称
     *
     * @return
     */
    public String getNickRowName(String name) {
        if (TextUtils.isEmpty(name)) {
            return "";
        }
        if (name.length() <= 2) {
            return name;
        } else {
            return name.substring(name.length() - 2, name.length());
        }

    }


    /**
     * 获取未读消息数
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        return unreadMsgCountTotal;
    }

    //从mainuiactivity 执行onresume方法来实时刷新消息数
    public void Imsets() {
        long messagenum = 0;
        messagenum= RunTimeManager.getInstance().getMessageNx();
        message_num_tz.setText(messagenum+"");
        if(messagenum>0) {
            message_num_tz.setVisibility(View.VISIBLE);
            if(messagenum>99) {
                message_num_tz.setVisibility(View.INVISIBLE);
//                message_num_99n.setVisibility(View.VISIBLE);
            }

        }else {
            message_num_tz.setVisibility(View.INVISIBLE);
//            message_num_99n.setVisibility(View.INVISIBLE);
        }


        getUnreadMsgCountTotal();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!NetStateUtils.isNetworkConnected(getActivity())){
            Toast.makeText(getActivity(),R.string.zanwus,Toast.LENGTH_SHORT).show();
        }
        Imsets();
    }
}